package com.example.dingding.service.impl;

import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.example.dingding.config.HttpHelper;
import com.example.dingding.constants.SystemConstants;
import com.example.dingding.entity.vo.AuthVO;
import com.example.dingding.entity.vo.UserInfoVO;
import com.example.dingding.service.LoginService;
import com.example.dingding.util.DdConfigSign;
import com.example.dingding.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 登录服务实现类
 *
 * @author zhaojinglong
 * @date 2024/2/23 10:30
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private HttpHelper httpHelper;

    @Override
    public ResponseResult auth(String type) {
        try {
            //获取与微应用的jsapi_ticket
            String jsapiTicket = httpHelper.getJsapiTicket();
            // 时间戳
            long timeStamp = System.currentTimeMillis();
            //随机字符串
            String nonceStr = UUID.randomUUID().toString();
            if (SystemConstants.USRCAR_JSAUTH_TYPE.equals(type)) {
                String signature = DdConfigSign.sign(jsapiTicket, nonceStr, timeStamp, SystemConstants.USRCAR_JSAUTH_URL);
                //获取Jsapi签名
                AuthVO authVO = new AuthVO();
                authVO.setAppId(httpHelper.getAgentid());
                authVO.setCorpId(httpHelper.getCorpid());
                authVO.setNonceStr(nonceStr);
                authVO.setTimeStamp(timeStamp);
                authVO.setSignature(signature);

                return ResponseResult.okResult(authVO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getUserInfo(List<String> userIds) {
        String accessToken = httpHelper.getAccess_Token();
        List<UserInfoVO> userInfoVOList = userIds.stream().map(userId -> {
            OapiV2UserGetResponse rsp = null;
            try {
                rsp = httpHelper.getUserInfo(userId,accessToken);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //手机号
            String mobile = rsp.getResult().getMobile();
            //姓名
            String name = rsp.getResult().getName();
            return new UserInfoVO(userId, name, mobile);
        }).collect(Collectors.toList());
        return ResponseResult.okResult(userInfoVOList);
    }
}
